package thread2;

/**
 * suspend/resume
 */
public class SuspendTest {

    static Object food = null;

    static void normal() throws InterruptedException {
        Thread thread = new Thread(() -> {
            while (food == null) {
                System.out.println("no food waiting ...");
                Thread.currentThread().suspend();
            }
            System.out.println("get food, go home.");
        });
        thread.start();
        Thread.sleep(2000L);
        food = new Object();
        System.out.println("wake up the thread");
        thread.resume();
    }

    /**
     * deadlock with synchronized
     * @throws InterruptedException
     */
    static void sync() throws InterruptedException {
        Thread thread = new Thread(() -> {
            while (food == null) {
                synchronized (SuspendTest.class) {
                    System.out.println("no food waiting ...");
                    Thread.currentThread().suspend();
                }
            }
            System.out.println("get food, go home.");
        });
        thread.start();
        Thread.sleep(2000L);
        food = new Object();
        synchronized (SuspendTest.class) {
            System.out.println("wake up the thread");
            thread.resume();
        }
    }

    /**
     * deadlock - miss notify
     * @throws InterruptedException
     */
    static void missNotify() throws InterruptedException {
        Thread thread = new Thread(() -> {
            while (food == null) {
                try {
                    Thread.sleep(3000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("no food waiting ...");
                Thread.currentThread().suspend();
            }
            System.out.println("get food, go home.");
        });
        thread.start();
        Thread.sleep(2000L);
        food = new Object();
        System.out.println("wake up the thread");
        thread.resume();
    }

    public static void main(String[] args) throws InterruptedException {
//        normal();
//        sync();
        missNotify();
    }
}
